package com.lyy.common.utils;

import com.lyy.system.pojo.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;

/**
 * @author 俞伟
 * @version 1.0
 * @date 2020/10/24
 * @description com.lyy.common.utils
 */

public class ShiroUtils {
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout() {
        getSubject().logout();
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public static SysUser getUser() {
        SysUser user = null;
        Object obj = getSubject().getPrincipal();
        if (null != obj) {
            user = new SysUser();
            BeanUtils.copyProperties(user, obj);
        }
        return user;
    }

    public static void setSysUser(SysUser user) {
        Subject subject = getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    /**
     * 获取用户id
     *
     * @return
     */
    public static String getUserId() {
        return getUser().getId();
    }

    /**
     * 获取用户账号
     *
     * @return
     */
    public static String getUsername() {
        return getUser().getUsername();
    }

    /**
     * 获取ip信息
     *
     * @return
     */
    public static String getIp() {
        return getSubject().getSession().getHost();
    }

    /**
     * 获取sessionId
     *
     * @return
     */
    public static String getSessionId() {
        return String.valueOf(getSubject().getSession().getId());
    }
}
